<template>
  <view class="container">
    <!-- 头部搜索区 -->
    <!-- <view class="search-bar">
      <view
        class="search-box"
        @tap="toSearchPage"
      >
        <image
          src="@/static/images/icon/search.png"
          class="search-img"
        />
        <text class="sear-input">
          搜索您想要的商品
        </text>
      </view>
    </view> -->
    <!-- 滚动内容区 -->
    <view class="main">
      <!-- 左侧菜单start -->
      <scroll-view
        scroll-y="true"
        class="leftmenu"
      >
        <block
          v-for="(item, index) in categoryList"
          :key="index"
        >
          <view
            :class="'menu-item ' + (selIndex==index?'active':'') + ' '"
            :data-index="index"
            :data-id="item.categoryId"
            @tap="onMenuTab"
          >
            <text class="menu-text">{{ item.categoryName }}</text>
          </view>
        </block>
        <view
          v-if="!categoryList.length"
          class="ca-empty"
        >
          {{ categoryList && categoryList.length ? '该分类下暂无商品' : '暂无商品' }}
        </view>
      </scroll-view>
      <!-- 左侧菜单end -->

      <!-- 右侧内容start -->
      <scroll-view
        scroll-y="true"
        class="rightcontent"
        @scrolltolower="onReachBottom"
        refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
      >
        <!-- 加载中提示 -->
        <view v-if="isLoading" class="loading-container">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 商品列表 -->
        <view class="cont-item" v-if="!isLoading">
          <block v-if="prodList.length">
            <view
              v-for="(item, index) in prodList"
              :key="item.prodId"
              class="show-item"
              @tap="toProdPage(item.prodId)"
            >
              <view class="more-prod-pic">
                <image
                  class="more-pic"
                  :src="item.pic"
                  mode="aspectFill"
                  lazy-load="true"
                ></image>
              </view>
              <view class="prod-text-right">
                <view class="prod-text more">{{ item.prodName }}</view>
                <view class="cate-prod-info">{{ item.brief }}</view>
                <view class="prod-price more">{{ item.price }}</view>
              </view>
            </view>
            <!-- 加载更多提示 -->
            <view class="load-more" v-if="prodList.length > 0">
              <text v-if="current < pages" class="loading"></text>
              <text>{{ current < pages ? '正在加载更多...' : '已经到底啦~' }}</text>
            </view>
          </block>
          <view
            v-else
            class="cont-item empty"
          >
            暂无商品数据~
          </view>
        </view>
      </scroll-view>
      <!-- 右侧内容end -->
    </view>
  </view>
</template>

<script setup>
import util from '@/utils/util.js'
const wxs = number()

const categoryList = ref([])
const prodList = ref([])
const categoryImg = ref('')
const parentId = ref('')

// 分页相关
const current = ref(1)
const pages = ref(0)
const isLoaded = ref(false)
const isLoading = ref(false)
const isRefreshing = ref(false)

/**
 * 生命周期函数--监听页面加载
 */
onLoad(() => {
  // 尝试从本地缓存获取分类列表
  const cachedCategoryList = util.getStorage('categoryList')
  
  if (cachedCategoryList) {
    // 使用缓存数据
    categoryImg.value = cachedCategoryList[0].pic
    categoryList.value = cachedCategoryList
    if (cachedCategoryList.length > 0) {
      // 尝试从缓存获取第一个分类的商品数据
      const firstCategoryId = cachedCategoryList[0].categoryId
      const cachedProdList = util.getStorage(`prodList_${firstCategoryId}`)
      
      if (cachedProdList) {
        // 使用缓存商品数据
        prodList.value = cachedProdList.records || []
        current.value = cachedProdList.current || 1
        pages.value = cachedProdList.pages || 0
        isLoaded.value = true
        isLoading.value = false
      } else {
        // 没有缓存商品数据，从网络获取
        getProdList(firstCategoryId)
      }
      parentId.value = firstCategoryId
    }
  } else {
    // 没有缓存分类数据，从网络获取
    loadCategoryList()
      .then((data) => {
        if (data && data.length > 0) {
          getProdList(data[0].categoryId)
        }
      })
  }
})

/**
 * 加载分类列表
 */
const loadCategoryList = () => {
  return http.request({
    url: '/category/categoryInfo',
    method: 'GET',
    data: {
      parentId: ''
    }
  })
    .then(({ data }) => {
      categoryImg.value = data[0].pic
      categoryList.value = data
      // 缓存分类数据
      util.setStorage('categoryList', data)
      
      if (data.length > 0) {
        // 保持当前选中的分类索引，如果当前分类不存在则重置为0
        const currentCategoryId = categoryList.value[selIndex.value]?.categoryId
        const newIndex = currentCategoryId ? data.findIndex(item => item.categoryId === currentCategoryId) : 0
        const validIndex = newIndex >= 0 ? newIndex : 0
        
        selIndex.value = validIndex
        parentId.value = data[validIndex].categoryId
      }
      return data
    })
}

const selIndex = ref(0)
/**
 * 分类点击事件
 */
const onMenuTab = (e) => {
  const index = e.currentTarget.dataset.index
  const categoryId = categoryList.value[index].categoryId
  
  current.value = 1
  pages.value = 0
  isLoading.value = true // 显示loading
  prodList.value = [] // 清空当前列表
  parentId.value = categoryId
  categoryImg.value = categoryList.value[index].pic
  selIndex.value = index
  
  // 尝试从缓存获取商品数据
  const cachedProdList = util.getStorage(`prodList_${categoryId}`)
  
  if (cachedProdList) {
    // 使用缓存商品数据
    prodList.value = cachedProdList.records || []
    current.value = cachedProdList.current || 1
    pages.value = cachedProdList.pages || 0
    isLoaded.value = true
    isLoading.value = false
  } else {
    // 没有缓存商品数据，从网络获取
    getProdList(categoryId)
  }
}

/**
 * 下拉刷新处理函数
 */
const onRefresh = () => {
  isRefreshing.value = true
  
  // 获取当前选中的分类ID
  const currentCategoryId = categoryList.value[selIndex.value]?.categoryId
  
  // 清除当前分类的缓存
  if (currentCategoryId) {
    util.removeStorage(`prodList_${currentCategoryId}`)
  }
  
  // 清除分类列表缓存
  util.removeStorage('categoryList')
  
  // 重置分页状态
  current.value = 1
  pages.value = 0
  prodList.value = []
  
  // 重新加载分类和商品数据
  loadCategoryList()
    .then(() => {
      if (categoryList.value.length > 0) {
        // 使用更新后的parentId，它已经在loadCategoryList中被正确设置
        return getProdList(parentId.value)
      }
    })
    .finally(() => {
      isRefreshing.value = false
    })
}

/**
 * 页面上拉触底事件的处理函数
 */
const onReachBottom = () => {
  if (current.value < pages.value) {
    current.value = current.value + 1
    getProdList(parentId.value)
  }
}

/**
 * 跳转搜索页
 */
const toSearchPage = () => {
  uni.navigateTo({
    url: '/pages/search-page/search-page'
  })
}

/**
 * 根据分类id获取商品列表数据
 */
const getProdList = (categoryId) => {
  isLoaded.value = false

  return http.request({
    url: '/prod/pageProd',
    method: 'GET',
    data: {
      categoryId: categoryId,
      current: current.value,
      size: 10,
      sort: 0,
      isAllProdType: true
    }
  })
    .then(({ data }) => {
      isLoaded.value = true
      isLoading.value = false // 隐藏loading
      let records = data.records

      // 按商品名称进行排序
      records.sort((a, b) => {
        return a.prodName.localeCompare(b.prodName, 'zh-CN')
      })

      let newProdList = []
      if (current.value === 1) {
        newProdList = records
      } else {
        newProdList = prodList.value.concat(records)
      }
      
      prodList.value = newProdList
      current.value = data.current
      pages.value = data.pages
      
      // 缓存商品数据
      const prodData = {
        records: newProdList,
        current: data.current,
        pages: data.pages
      }
      util.setStorage(`prodList_${categoryId}`, prodData)
      
      return data
    })
    .catch(() => {
      isLoading.value = false // 出错时也隐藏loading
      isLoaded.value = true
    })
}

/**
 * 跳转商品详情页
 */
const toProdPage = (prodId) => {
  uni.navigateTo({
    url: '/pages/prod/prod?prodid=' + prodId
  })
}

/**
 * 分享设置
 */
onShareAppMessage(() => {
  return {
    title: '瀚微精测 - 专业的检测服务',
    path: '/pages/index/index',
  };
});

/**
 * 分享到朋友圈
 */
onShareTimeline(() => {
  return {
    title: '瀚微精测 - 专业的检测服务',
    path: '/pages/index/index',
  };
});
</script>

<style scoped lang="scss">
@import "./category.scss";
</style>
